package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.feign.article.IArticleClient;
import com.heima.model.apuser.dtos.NewsAuthDto;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.constants.WemediaConstants;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author rookie001
 * @creat 2023-06-07-20:58
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    //查询自媒体文章
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //数据校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //获取用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());///先page再size
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //根据状态判断
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //根据频道判断
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //根据开始结束时间判断
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //模糊查询关键字
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //查询当前登录用户文章
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());
        //发布时间倒叙顺序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        //返回结果
        page = page(page, lambdaQueryWrapper);///////////////////返回数据给page
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());////////////
        return responseResult;
    }


    //   发布文章或保存草稿
    @Override
//    @Transactional
    public ResponseResult submitNews(WmNewsDto dto) {

        //数据判断
        if (dto == null || dto.getChannelId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //获取图片
        List<String> images = dto.getImages();
        if (images.size() > 0 && images != null) {
            //处理图片格式
            String image = StringUtils.join(images, ",");
            wmNews.setImages(image);
        }
        //如果封面类型为自动 则修改为null
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //保存或修改文章
        saveOrUpdateWmNews(wmNews);
        //判断是否为草稿  是则结束
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是草稿 
        //获取文章中内容的图片
        List<String> materials = ectractUrlInfo(dto.getContent());
        //保存 文章 内容图片 与素材的关系
        saveRelativeInfoForContent(materials, dto.getId());
        //不是草稿 保存 文章 封面图片 的素材关系
        saveRelativeInfoForCover(dto, wmNews, materials);

        //自动审核 异步调用
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //文章发布添加到延时队列
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    // 保存和修改文章
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);//上架
        if (wmNews.getId() == null) {
            //保存
            save(wmNews);
        } else {
            //修改
            wmNewsMaterialMapper.delete(Wrappers
                    .<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    //  获取文章内容图片
    private List<String> ectractUrlInfo(String content) {
        List<String> url = new ArrayList<String>();
        List<Map> images = JSONArray.parseArray(content, Map.class);
        for (Map image : images) {
            if (image.get("type").equals("image")) {
                String value = (String) image.get("value");
                url.add(value);
            }
        }
        return url;
    }

    //保存 文章 内容图片 与素材的关系                                      文章id
    private void saveRelativeInfoForContent(List<String> materials, Integer id) {
        //保存文章图片与素材的关系到数据库中
        saveRelativeInfo(materials, id, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    //保存文章图片与素材的关系到数据库中
    private void saveRelativeInfo(List<String> images, Integer id, Short type) {
        //数据校验
        if (images != null && !images.isEmpty()) {
            //获取素材图片
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));
            //判断素材是否有效
            if (wmMaterials == null && !wmMaterials.isEmpty()) {
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            if (images.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            //根据url获取素材id
            List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //批量保存
            wmNewsMaterialMapper.saveRelations(ids, id, type);
        }
    }

    //    保存 文章 封面图片 的素材关系
    //     * 功能一 匹配规则 自动 -1时
    //     * 图片数 0 无图
    //     *   小于 3 单图
    //     *   大于等于 3 多图
    //     * 第二个功能：保存封面图片与素材的关系
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            ///前面置为null 现在设置
            if (materials.size() >= 3) {
                //多图
                wmNews.setType((short) 3);
                //截取三张
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else if (materials.size() >= 1 && materials.size() < 3) {
                //单图
                wmNews.setType((short) 1);
                //截取一张
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType((short) 0);
            }

            //修改文章   如果上面方法有走 就是自动插入图片   没有就是自己选择
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            //更新表
            updateById(wmNews);
        }
        //保存文章图片与素材的关系到数据库中
        if (images != null && images.size() > 0) {
            saveRelativeInfo(images, wmNews.getId(), (short) 1);
        }
    }

    //文章上下架
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
//        //数据校验
//        if (dto == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
//        }
//        //获取当前文章
//        WmNews wmNews = getById(dto.getId());
//        if (wmNews == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
//        }
//        //判断是否发布
//        if (wmNews.getStatus() == 1) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章还未发布，不能上下架");
//        }
//        //修改wm_news
//        update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable())
//                .eq(WmNews::getId, dto.getId()));
//
//        //发送者 向app端发送
//        if (wmNews.getArticleId() != null) {
//            Map<String, Object> map = new HashMap();
//            map.put("articleId", wmNews.getArticleId());
//            map.put("enable", wmNews.getEnable());
//            //发送消息 1 topic  2  发送的数据
//            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
//        }
//        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
//    }

        //数据校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否发布
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章还未发布");
        }
        //修改数据库  ap_article
        update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable()).eq(WmNews::getId, wmNews.getId()));
        //kafka发送消息
        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());/////////////////////失误可能没提交
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));//序列化成json
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    private WmUserMapper wmUserMapper;

    //管理端分页查询
    @Override
    public ResponseResult getNewsList(NewsAuthDto dto) {
        //数据校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页判断
        dto.checkParam();
        //设置分页条件
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //模糊查询内容
        if (dto.getMsg() != null) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getMsg());
        }
        //按照选择类型查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //按照创建时间查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        //封装分页
        page = page(page, lambdaQueryWrapper);
        // 返回作者
        List<WmUserDto> wmUserDtos = new ArrayList<>();
//
        List<WmNews> wmNews = page.getRecords();
//
        for (WmNews wmNew : wmNews) {
            WmUserDto wmUserDto = new WmUserDto();
            BeanUtils.copyProperties(wmNew, wmUserDto);
            WmUser wmUser = wmUserMapper.selectById(wmNew.getUserId());
            String name = wmUser.getName();
            wmUserDto.setAuthorName(name);
            wmUserDtos.add(wmUserDto);
        }
        page.setRecords(wmUserDtos);
        //返回数据
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    //文章详情
    @Override
    public ResponseResult getNewsDetail(Integer id) {
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        WmUserDto wmUserDto = new WmUserDto();
        BeanUtils.copyProperties(wmNews, wmUserDto);
        wmUserDto.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(wmUserDto);

    }


    //文章审核驳回
    @Override
    public ResponseResult auditReject(NewsAuthDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        wmNews.setStatus((short) 2);
        wmNews.setReason(dto.getMsg());
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @Autowired
    private IArticleClient iArticleClient;
    //文章审核成功
    @Override
    public ResponseResult auditPass(NewsAuthDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        wmNews.setStatus((short) 9);
        wmNews.setReason("审核成功");
        updateById(wmNews);
        //保存到app端
        ArticleDto articleDto=new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        articleDto.setContent(dto.getTitle());
        iArticleClient.saveArticle(articleDto);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
